#include "sensordatadisplayinterface.h"
#include "ui_sensordatadisplayinterface.h"
Q_GLOBAL_STATIC(SensorDataDisplayInterface,theInstance);


SensorDataDisplayInterface::SensorDataDisplayInterface(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SensorDataDisplayInterface)
{
    ui->setupUi(this);
    this->setWindowTitle("历史数据显示界面");
    this->setWindowIcon(QIcon(":res/res/HistoricalData.ico"));
}

SensorDataDisplayInterface *SensorDataDisplayInterface::instance()
{


return theInstance;

}
SensorDataDisplayInterface::~SensorDataDisplayInterface()
{
    delete ui;
}

void SensorDataDisplayInterface::displaySensorData()
{

   // 2. 创建模型并绑定表
        model = new QSqlTableModel(this,UserMysqlS::instance()->getDataBase());
        model->setTable("sensordatastand");

        // 3. 设置列标题（字段名到中文的映射）
        model->setHeaderData(0,Qt::Horizontal,"id");
        model->setHeaderData(1, Qt::Horizontal, "时间");
        model->setHeaderData(2, Qt::Horizontal, "空气温度");
        model->setHeaderData(3, Qt::Horizontal, "空气湿度");
        model->setHeaderData(4, Qt::Horizontal, "光照强度");
        model->setHeaderData(5, Qt::Horizontal, "CO2浓度");
        model->setHeaderData(6, Qt::Horizontal, "土壤湿度");

        // 4. 加载数据
        if (!model->select()) {
            QMessageBox::critical(this, "错误", "查询失败: " + model->lastError().text());
            //UserMysqlS::instance()->getDataBase()->close();
            return;
        }

        // 5. 创建视图并绑定模型
       // QTableView *tableView = new QTableView(this);
        ui->tableViewSensorDisplay->setModel(model);
        //tableView->setModel(model);
        ui->tableViewSensorDisplay->resizeColumnsToContents();//自适应
        ui->tableViewSensorDisplay->setSortingEnabled(true);//自动排序
        ui->tableViewSensorDisplay->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//可拉伸

        // 6. 布局
//        QVBoxLayout *layout = new QVBoxLayout(this);
//        layout->addWidget( ui->tableViewSensorDisplay);
//        setLayout(layout);

        // 注意：此处未关闭数据库连接，因为模型可能后续需要操作




}

void SensorDataDisplayInterface::on_pushButtonRestart_clicked()
{

    // 禁用按钮防止重复点击
        ui->pushButtonRestart->setEnabled(false);
        QApplication::processEvents();  // 立即更新UI

        // 重新加载数据
        if (!model->select()) {
            QMessageBox::critical(this, "错误", "刷新失败: " + model->lastError().text());
        } else {
            // 滚动到最新数据（假设按时间降序排序）
            ui->tableViewSensorDisplay->scrollToTop();
        }

        // 恢复按钮状态
        ui->pushButtonRestart->setEnabled(true);






}


void SensorDataDisplayInterface::on_pushButtonBack_clicked()
{
    this->close();
}

